let express = require('express');
let jwt = require('jsonwebtoken');
let constant = require('../../../private/constant')
let db = require('../../../tools/database');
let util = require('../../../tools/util')

let router = express.Router();


// 验证注册链接
// 错误处理标准化 √√
router.use(function (req, res, next) {
	let urlToken = req.query.urlToken;
	let token = urlToken.replace("@@", '.').replace("@@", '.');
	jwt.verify(token, constant.secretKey, function (err, decoded) {
		if (err) {
			// ! JWT验证错误
			util.errorRespond('JWT_VERIFY_ERROR', err, res)
		} else {
			// % JWT验证成功, 添加数据到数据库
			let netID = decoded.netID
			let userName = decoded.userName
			let userKey = decoded.key
			let sql = "SELECT * FROM Users Where NetID=?";
			db.queryCallback(sql, [netID], res, (result)=>{
				if(result.length !== 0){
					res.render('baseReminder/INDEX', {
						reminder: `<h3>已经注册成功，请不要重新注册</h3>
						<a href="/index" class="btn btn-success"返回主页 &raquo;</a>`
					})
				}else{
					let sql = `INSERT INTO Users  (NetID, UserName, UserKey) value (?, ?, ?)`;
					db.queryCallback(sql, [netID, userName, userKey], (result) => {
						res.render('baseReminder/INDEX', {
							reminder: `<h3>注册成功</h3><hr><h5>邮箱前缀: ${netID}</h5>  <h5>用户名: ${userName}</h5> <br> <h5>登录后即可发布闲置 | 进入用户页可以完善联系方式/改变商品上架状态</h5> <br> ` +
								`<a href="/login" class="btn btn-success">现在登录 &raquo;</a>`
						})
					})

				}
			}, false, false)
		}
	})

});

module.exports = router;